package com.power.project.dao.impl;

import com.power.project.dao.Ww_departDaoCustom;
import com.power.project.model.Ww_depart;
import com.power.project.model.vo.DepartLeaderForSetVO;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;

import static com.power.project.dao.impl.Ww_userDaoImpl.BLANK_STRING;

/**
 * 企业微信部门信息 持久层实现(hibernate)
 */

@Repository
public class Ww_departDaoImpl implements Ww_departDaoCustom<Ww_depart, Serializable> {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<DepartLeaderForSetVO> findByDepartIdAndTenantId(String departid, String tenantid) {
        StringBuilder dataSql = new StringBuilder(" select wu.userid as \"userId\", wu.name, wdu.isleader as \"isLeader\"\n" +
                "from ww_user wu left join ww_depart_user wdu on wu.userid = wdu.wwuserid "+
                "left join ha_user hu on wu.userid = hu.userid and hu.deleted = 0").append(BLANK_STRING);
        StringBuilder whereSql = new StringBuilder("where wdu.departid = :departid and wdu.tenantid = :tenantid and hu.userid is not null");
        dataSql.append(whereSql);
        Query dataQuery = entityManager.createNativeQuery(dataSql.toString());

        dataQuery.setParameter("departid", departid);
        dataQuery.setParameter("tenantid", tenantid);

        return dataQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(DepartLeaderForSetVO.class)).getResultList();
    }
}